using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance{ get; private set; }
    public GameSO gameSo;//游戏数据
    
    public Bird[] birdList;//小鸟列表
    private int index = -1;//当前小鸟索引
    
    private int pigTotalCount = 0;//猪的总数
    private int pigDeadCount = 0;//死亡的猪的数量
    
    private FollowTarget cameraFollowTarget;//跟随目标
    
    public Game0verUI game0verUI;
    
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
        LoadSelectedLevel();
    }
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    //加载选中的关卡
    private void LoadSelectedLevel()
    {
        Time.timeScale = 1f;
        //获取游戏数据
        int mapID = gameSo.selectedMapID;
        int levelID = gameSo.selecteLevelID;
        
        Addressables.LoadAssetsAsync<GameObject>(new List<string>{"Map" + mapID, "Level" + levelID}, (handle) =>
        {
            Debug.Log($"符合的资源：{handle.name}");
            Instantiate(handle, Vector3.zero, Quaternion.identity, transform.parent);
            
            
            birdList = FindObjectsByType<Bird>(FindObjectsSortMode.None);
            pigTotalCount = FindObjectsByType<Pig>(FindObjectsSortMode.None).Length;
            cameraFollowTarget = Camera.main.GetComponent<FollowTarget>();
            LoadNextBird();
            
            
        }, Addressables.MergeMode.Intersection);
        
    }
    
    //加载下一个小鸟
    public void LoadNextBird()
    {
        index++;
        //如果小鸟列表已经遍历完，则返回
        if (index >= birdList.Length)
        {
            GameOver();
            return;
        }
        birdList[index].GoStage(Slingshot.Instance.GetCenterPoint());//小鸟进入舞台
        cameraFollowTarget.SetTarget(birdList[index].transform);//跟随小鸟
    }
    
    public void OnPigDead()
    {
        pigDeadCount++;
        if (pigDeadCount >= pigTotalCount)
        {
            GameOver();
        }
    }

    private void GameOver()
    {
        int starCount = 0;
        float pigDeadPercent = pigDeadCount * 1f / pigTotalCount;
        if (pigDeadPercent >= 0.99f)
        {
            starCount = 3;
        }
        else if (pigDeadPercent >= 0.66f)
        {
            starCount = 2;
        }
        else if (pigDeadPercent >= 0.33f)
        {
            starCount = 1;
        }
        game0verUI.Show(starCount);
        gameSo.UpdateLevel(starCount);
    }

    public void RestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);//重新加载当前场景
    }

    public void LevelList()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }
    //1加载界面 2地图和关卡选择 3游戏场景
}
